import { defineStore } from 'pinia';
import { ref } from 'vue';
import api from '@/http/api';

export const useAreaStore = defineStore('area', () => {
  const areaList = ref([]);
  const loading = ref(false);

  const setAreaList = (list) => {
    areaList.value = list;
  };

  const clearAreaList = () => {
    areaList.value = [];
  };

  const getAreaList = async() => {
    if (areaList.value && areaList.value.length > 0) {
      return areaList.value;
    }

    if (loading.value) {
      await sleep(100);
      return await getAreaList();
    }

    loading.value = true;
    const res = await api.post('/area/tree').catch(() => {
      loading.value = false
    });
    if (res.code === '1') {
      loading.value = false;
      setAreaList(res.data.children || []);
      return areaList.value;
    }
  };

  const sleep = async (d) => {
    return new Promise((resolve) => setTimeout(resolve, d))
  };

  return {
    getAreaList,
    clearAreaList
  };
});
